//
//  ZDPictureView.swift
//  1026SwiftSinaWeiBo
//
//  Created by Apple on 15/11/1.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import SDWebImage

//通知定义在类的外面 表示全局的 在其他地方都可以访问
let ZDPictureViewCellSelectedNotification = "ZDPictureViewCellSelectedNotification"
//定义两个key
let ZDPictureViewCellSelectedIndexPathKey = "ZDPictureViewCellSelectedIndexPathKey"
let ZDPictureViewCellStatusModelKey = "ZDPictureViewCellStatusModelKey"


class ZDPictureView: UICollectionView {
    
    let reuseIdentifier: String = "ZDPictureViewCell"
    
    var status: ZDStatus? {
    
        didSet {
        
            reloadData()
        }
    }
    
    //布局属性
    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()

    //MARK: - 构造方法
    init() {
    
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        prepareUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //MARK: - 准备UI
    private func prepareUI() {
        
        backgroundColor = UIColor.clearColor()
    
        //指定数据源
        dataSource = self
        
        //指定代理
        delegate = self
        
        //注册cell
        registerClass(ZDPictureViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }
    
    
    //MARK: - 计算size
    func calculateSize() -> CGSize {
        
        //设置默认itemSize
        let itemSize = CGSize(width: 90, height: 90)
        
        //设置默认的间距
//        layout.minimumInteritemSpacing = 0
//        layout.minimumLineSpacing = 0
        
        //定义间距
        let margin = CGFloat(10)
        
        //定义列数 ———— 最多3行3列
        let colown = 3
    
        let count = status?.pictureURLs?.count ?? 0
        
        //没有配图
        if count == 0 {
        
            return CGSizeZero
        }
        
        //只有一张配图 返回图片原有尺寸
        if count == 1 {
        
            let url = status?.pictureURLs![0].absoluteString
            
            var size = CGSize(width: 150, height: 120)
            
            //从缓存加载图片
            if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(url) {
            
                size = image.size
                
                size.width = image.size.width > UIScreen.width-2*margin ? UIScreen.width-2*margin : image.size.width
            }
            
            if size.width < 40 {
            
                size.width = 40
            }
            
            layout.itemSize = size
            return size
        }
        
        
        //设置item之间的间距
        layout.minimumInteritemSpacing = margin
        layout.minimumLineSpacing = margin
        layout.itemSize = itemSize
        
        //有4张配图 两行两列
        if count == 4 {
            
            let width = CGFloat(2) * 90 + margin
            let height = width
            
            return CGSize(width: width, height: height)
        }
        
        
        //配图数为 2、3、5、6、7、8、9 固定按3列显示
        let row = (count + colown-1) / colown
        
        let width = CGFloat(colown * 90) + CGFloat(colown-1) * margin
        
        let height = CGFloat(row * 90) + CGFloat(row-1) * margin
        
        return CGSize(width: width, height: height)
    }
    
}


//MARK: - 在当前类的扩展中 实现UICollectionViewDataSource 数据源方法
extension ZDPictureView: UICollectionViewDataSource, UICollectionViewDelegate {

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return status?.pictureURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! ZDPictureViewCell
        
//        cell.backgroundColor = UIColor.randomColor()
        
//        if let urlString = status?.pic_urls?[indexPath.item]["thumbnail_pic"] as? String {
//        
//            cell.imageURL = NSURL(string: urlString)
//        }
        
        cell.imageURL = status?.pictureURLs?[indexPath.item]
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        //通知控制器被点击  控制器呼出图片查看器
        //传参：1.索引indexPath.item   2.所点击的图片的大图URL
        
        //创建模型数组
        var models = [ZDPhotoBrowserModel]()
        
        let count = status!.largePictureURLs!.count
        
        for i in 0..<count {
        
            let url = status?.largePictureURLs![i]
            
            let indexPathNew = NSIndexPath(forItem: i, inSection: 0)
            
            let cell = collectionView.cellForItemAtIndexPath(indexPathNew) as! ZDPictureViewCell
            
            let imageView = cell.pictureView
            
            let model = ZDPhotoBrowserModel(url: url, imageView: imageView)
            
            models.append(model)
        }
        
        //定义附加信息字典
        let userInfo: [String: AnyObject] = [
         
            ZDPictureViewCellSelectedIndexPathKey: indexPath.item,
            ZDPictureViewCellStatusModelKey: models
        ]
        
        NSNotificationCenter.defaultCenter().postNotificationName(ZDPictureViewCellSelectedNotification, object: self, userInfo: userInfo)
    }
}



class ZDPictureViewCell: UICollectionViewCell {
    
    //MARK: - 属性
    var imageURL: NSURL? {
    
        didSet {
        
            pictureView.zd_setImageWithURL(imageURL)
            
            //取出路径的后缀，转成小写
            let isGif = (imageURL!.absoluteString as NSString).pathExtension.lowercaseString == "gif"
            
            gifView.hidden = !isGif
        }
    }

    //MARK: - 构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        prepareUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //MARK: - 准备UI
    private func prepareUI() {
    
        //添加子控件
        contentView.addSubview(pictureView)
        contentView.addSubview(gifView)
        
        //添加约束
        pictureView.ff_Fill(contentView)
        gifView.ff_AlignInner(type: ff_AlignType.BottomRight, referView: contentView, size: nil)
    }

    //MARK: - 懒加载
    lazy var pictureView: UIImageView = {
    
        let imageView = UIImageView()
        
        //设置填充模式  ———— 等比缩放填充
        imageView.contentMode = UIViewContentMode.ScaleAspectFill
        
        //裁剪超出的部分
        imageView.clipsToBounds = true
        
        return imageView
    }()
    
    //gif标识view
    private lazy var gifView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
}
